<template>
  <div class="add-box">
    <el-form :model="form" label-position="top" :rules="formRules" ref="ruleForm">
      <el-form-item label="编号">
        <el-input v-model="form.productNum"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="productName">
        <el-input v-model.number="form.productName" class="input-with-select"></el-input>
      </el-form-item>
      <el-form-item label="类别" prop="customerChannel">
        <el-cascader
          v-model="form.customerChannel"
          :show-all-levels="false"
          :options="typeOptions"
          :props="{value: 'id',label: 'name', checkStrictly: true, emitPath: false}"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="型号">
        <el-input v-model="form.productModel"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('changeState',false)">取 消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </div>
  </div>
</template>
<script>
import { save } from '@/api/product'
import { findList } from '@/api/type'
export default {
  data() {
    return {
      date: '',
      form: {
        companyId: this.$store.state.user.companyId,
        productNum: '',
        productName: '',
        customerChannel: '',
        productModel: ''
      },
      typeOptions: [],
      formRules: {
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        customerChannel: [
          { required: true, message: '请选择客户类型', trigger: 'blur' }
        ]
      }
    }
  },
  beforeDestroy() {
    this.$off('reload')
    this.$off('changeState')
  },
  mounted() {
    this.initTypeOptions()
  },
  methods: {
    initTypeOptions() {
      findList(this.form.companyId, 1).then(res => {
        this.typeOptions = res.data
      })
    },
    submit() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          save(this.form).then(res => {
            if (res.success) {
              this.$emit('reload')
              this.$emit('changeState', false)
              this.$message.success(res.message)
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.add-box {
  padding: 0 50px;
}
.dialog-footer {
  text-align: right;
}
</style>
